package com.wangzhenyu.common.netcore.coroutine

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlin.coroutines.CoroutineContext

class CoroutineSupport(parent: Job? = null) : CoroutineScope, DefaultLifecycleObserver {

    private val job: Job = if (parent == null) {
        SupervisorJob()
    } else {
        SupervisorJob(parent)
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        job.cancel()
    }

    fun cancelChildren() {
        job.cancelChildren()
    }
}